# !/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'Liu DengFeng'

import os
import shutil
import base64

def save_chunk(key, file_id, chunk_index, data, temp_folder):
    """
    保存分片数据到临时目录。

    :param key: 分片对应的属性名
    :param file_id: 文件标识符
    :param chunk_index: 当前分片的索引
    :param data: 分片数据
    :param temp_folder: 临时存储分片的根目录
    """
    temp_key_folder = os.path.join(temp_folder, file_id, key)
    os.makedirs(temp_key_folder, exist_ok=True)

    temp_file_path = os.path.join(temp_key_folder, f"chunk_{chunk_index}")
    if isinstance(data, str):  # 如果是字符串数据（非 Blob 类型）
        with open(temp_file_path, "w") as f:
            f.write(data)  # 将字符串写入文件
    else:  # 如果是 Blob 数据
        data.save(temp_file_path)  # 保存为二进制文件

    return temp_key_folder

# def merge_chunks(key, file_id, total_chunks, temp_folder, upload_folder):
#     """
#     合并所有分片数据为完整文件。

#     :param key: 属性名
#     :param file_id: 文件标识符
#     :param total_chunks: 总分片数量
#     :param temp_folder: 临时存储分片的根目录
#     :param upload_folder: 最终文件存储目录
#     """
#     temp_key_folder = os.path.join(temp_folder, file_id, key)
#     final_file_path = os.path.join(upload_folder, f"{file_id}_{key}")

#     with open(final_file_path, "wb") as final_file:
#         for i in range(total_chunks):
#             chunk_path = os.path.join(temp_key_folder, f"chunk_{i}")
#             with open(chunk_path, "rb") as chunk_file:
#                 final_file.write(chunk_file.read())  # 将每个分片内容写入最终文件

#             # 确保文件关闭后再删除
#             # try:
#                 # os.remove(chunk_path)
#             # except PermissionError:
#                 # time.sleep(0.1)  # 延迟后重试
#                 # os.remove(chunk_path)

#     # os.rmdir(temp_key_folder)  # 删除临时目录
#     return final_file_path


def merge_chunks(key, file_id, total_chunks, temp_folder, upload_folder):
    """
    合并所有分片数据为完整文件。

    :param key: 属性名
    :param file_id: 文件标识符
    :param total_chunks: 总分片数量
    :param temp_folder: 临时存储分片的根目录
    :param upload_folder: 最终文件存储目录
    :return: 合并后的文件路径
    """
    temp_key_folder = os.path.join(temp_folder, file_id, key)
    final_file_path = os.path.join(upload_folder, f"{file_id}_{key}")

    with open(final_file_path, "wb") as final_file:
        for i in range(total_chunks):
            chunk_path = os.path.join(temp_key_folder, f"chunk_{i}")
            if not os.path.exists(chunk_path):
                print(f"Chunk {i} at {chunk_path} does not exist.")
                continue

            with open(chunk_path, "rb") as chunk_file:
                final_file.write(chunk_file.read())  # 将每个分片内容写入最终文件

    return final_file_path


def delete_path(path):
    try:
        if os.path.isfile(path):  # 如果是文件
            os.remove(path)
            print(f"文件 {path} 已成功删除！")
        elif os.path.isdir(path):  # 如果是文件夹
            shutil.rmtree(path)
            print(f"文件夹 {path} 已成功删除！")
        else:
            print(f"{path} 不存在或不是有效路径。")
    except Exception as e:
        print(f"删除 {path} 时发生错误：{e}")


def is_all_chunks_uploaded(temp_key_folder, total_chunks):
    """
    检查是否接收到了所有分片。

    :param temp_key_folder: 临时目录路径
    :param total_chunks: 总分片数量
    :return: 是否所有分片已上传
    """
    uploaded_chunks = len([f for f in os.listdir(temp_key_folder) if f.startswith("chunk_")])
    return uploaded_chunks == total_chunks


def get_file_base64(file_path):
    """
    读取服务端合并后的文件，并返回 Base64 编码的数据。

    :param file_path: 服务端合并后的文件路径
    :return: Base64 编码字符串，或 None 如果文件不存在或读取失败
    """
    try:
        # 打开文件并读取内容
        with open(file_path, "rb") as file:
            file_content = file.read()  # 读取文件的二进制数据
            base64_data = base64.b64encode(file_content).decode("utf-8")  # 转为 Base64 编码
            return base64_data
    except FileNotFoundError:
        print(f"Error: File not found at {file_path}.")
        return None
    except Exception as e:
        print(f"Error reading file {file_path}: {e}")
        return None

